<script lang="ts" setup>
  import TableLayout from '@/layout/table-layout.vue';
  import { usePageTable } from '@/hooks/arco/usePageTable';
  import useModeModalHandler from '@/hooks/arco/useModeModalHandler';
  import { Message, Modal } from '@arco-design/web-vue';
  import { deleteElder, queryElders } from '@/api-new/elderly';
  import { onMounted, ref } from 'vue';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import { affiliatedYear, queryByParentCode, rating } from '@/api-new/dict';
  import EditModal from './edit.vue';

  // 定义API接口
  interface ElderlyRecord {
    elderlyId: string;
    name: string;
    idcardno: string;
    gender: string;
    age: number;
    phone: string;
    village: string;
    year: string;
    organization: string;
    address: string;
    rating: string;
    validityPeriod: string;
  }

  // 定义表格列
  const columns = [
    {
      title: '长者ID',
      width: 160,
      dataIndex: 'elderId',
    },
    {
      title: '长者姓名',
      dataIndex: 'name',
      width: '120',
    },
    {
      title: '身份证号',
      width: 200,
      dataIndex: 'idcardno',
    },
    {
      title: '性别',
      width: '80',
      dataIndex: 'gender',
      render: ({ record }: any) => {
        return record.gender === 1 ? '男' : '女';
      },
    },
    {
      title: '年龄',
      width: '80',
      dataIndex: 'age',
    },
    {
      width: '200',
      title: '手机号码',
      dataIndex: 'phoneNo',
    },
    {
      title: '所属村镇',
      width: '150',
      dataIndex: 'villageName',
      tooltip: true,
      ellipsis: true,
    },
    {
      title: '归属年度',
      width: '150',
      dataIndex: 'yearName',
    },
    {
      title: '归属机构',
      width: '120',
      dataIndex: 'institutionName',
    },
    {
      title: '家庭地址',
      width: '200',
      tooltip: true,
      ellipsis: true,
      dataIndex: 'address',
    },
    {
      title: '评级',
      width: '100',
      dataIndex: 'ratingLevelName',
    },
    {
      title: '保障有效期',
      width: '150',
      dataIndex: 'validDate',
      render: ({ record }: any) => {
        return `${record.startDate}-${record.validDate}`;
      },
    },
    {
      title: '操作',
      align: 'center' as const,
      dataIndex: 'action',
      slotName: 'action',
      fixed: 'right',
    },
  ];

  const page = usePageTable({
    searchForm: {
      state: {
        name: '',
        idcardno: '',
        phone: '',
        yearId: '',
        rating: '',
        addressCode: [],
      },
    },
    table: {
      rowKey: 'elderId',
      fakePage: true,
      apiFun: (query) => {
        const { addressCode, ...data } = query;

        if (addressCode) {
          const [
            provinceCode,
            cityCode,
            districtCode,
            streetCode,
            committeeCode,
          ] = addressCode;

          data.provinceCode = provinceCode;
          data.cityCode = cityCode;
          data.districtCode = districtCode;
          data.streetCode = streetCode;
          data.committeeCode = committeeCode;
        }

        return queryElders(data);
      },
      columns,
    },
  });

  // 处理批量导入
  const handleImport = () => {
    // TODO: 实现批量导入逻辑
  };

  // 处理批量导出
  const handleExport = () => {
    // TODO: 实现批量导出逻辑
  };

  const handler = useModeModalHandler({
    onSuccess() {
      page.reload();
    },
  });

  const addressOptions = ref([]);

  const yearSelect = useSelectOption({
    name: '所属年度',
    apiFun: affiliatedYear,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  const rateSelect = useSelectOption({
    name: '评级',
    apiFun: rating,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  onMounted(() => {
    queryByParentCode().then((res) => {
      addressOptions.value = res;
    });
  });

  const fieldNames = { value: 'areaCode', label: 'areaName' };

  const loadMore = (option: any, done: any) => {
    queryByParentCode(option.areaCode).then((res) => {
      if (option.areaLevel === 4) {
        res.forEach((element: any) => {
          element.isLeaf = true;
        });
      }
      done(res);
    });
  };

  const scroll = {
    x: 1890,
  };
</script>

<template>
  <div class="flex flex-col">
    <TableLayout
      :scrollbar="true"
      :scroll="scroll"
      v-bind="page.bindProps"
      @create="handler.showAdd"
    >
      <template #searchForm="{ state }">
        <a-form-item field="name" label="长者姓名">
          <a-input
            v-model="state.name"
            placeholder="请输入长者姓名"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="idcardno" label="身份证号">
          <a-input
            v-model="state.idcardno"
            placeholder="请输入身份证号码"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="phone" label="手机号码">
          <a-input
            v-model="state.phone"
            placeholder="请输入手机号码"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="village" label="所属村镇">
          <a-cascader
            v-model="state.addressCode"
            :options="addressOptions"
            placeholder="请选择所属村镇"
            :field-names="fieldNames"
            :load-more="loadMore"
            class="w-full"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="yearId" label="所属年度">
          <a-select
            v-model="state.yearId"
            v-bind="yearSelect.bindProps"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="ratingLevel" label="评级">
          <a-select
            v-model="state.ratingLevel"
            v-bind="rateSelect.bindProps"
            allow-clear
          />
        </a-form-item>
      </template>

      <template #action="{ record }">
        <a-space>
          <a-button
            size="small"
            type="text"
            @click="handler.showDetail(record)"
          >
            详情
          </a-button>
        </a-space>
      </template>
    </TableLayout>

    <!-- 编辑弹窗 -->
    <EditModal v-bind="handler.bindProps" />
  </div>
</template>

<style scoped></style>
